/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    ActivityIndicator,
    Animated,
    AsyncStorage,
    DeviceEventEmitter,
    Image,
    ListView,
    NativeModules,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import StyleUtils from "../../res/styles/StyleUtils";
import Navigation, {StatusBarTextStyle} from "../../custom/Navigation";
import ViewUtils from "../../utils/ViewUtils";
import SelectRegisterPage from "./register/SelectRegisterPage";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import FindPasswordPage from "./FindPasswordPage";
import IparNetwork, {SERVER_TYPE} from "../../httpUtils/IparNetwork";
import CommonUtils from "../../common/CommonUtils";
import SlideMenu from "../../menu/SlideMenu";
import I18n from "../../res/language/i18n";
import IparInput from "../../custom/IparInput";

const clickTypes = {register: 'REGISTER', login: 'LOGIN', forgotPass: 'FORGOT PASS'};
export default class LoginPage extends Component {


    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.countryData = null;
        this.state = {
            fadeAnim: new Animated.Value(0), // init opacity 0
        }
    }

    componentDidMount() {
        Animated.timing(  // Uses easing functions
            this.state.fadeAnim,  // The value to drive
            {
                toValue: 1,
                duration: 700
            },  // Configuration
        ).start(); // Don't forget start!


        this.onLoadCountryData();

    }


    /**
     * 获取各位国家的数据
     */
    onLoadCountryData(startLogin) {
        this.showLogin(true);
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', '')
            .then((result) => {
                this.showLogin(false);
                if (result && result.length >= 0) {
                    this.countryData = result;
                    if (startLogin) {
                        this.startLogin();
                    }
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.showLogin(false);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('LoginPage/--onLoadCountryData/-error-', error);
            })
    }

    /**
     * 数据加载效果
     * @param visible
     */
    showLogin(visible) {
        if (visible) {
            CommonUtils.showLoading()
        } else {
            CommonUtils.dismissLoading()
        }
    }

    /**
     * 登陆
     */
    startLogin() {
        if (!this.userName || !this.userName.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.iparIdUserName'));
            return
        }
        if (!this.userPass || !this.userPass) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterPass'));
            return
        }
        this.showLogin(true);
        let formData = new FormData();
        formData.append('name', this.userName);
        formData.append('password', this.userPass);
        this.iparNetwork.getPostFrom(SERVER_TYPE.centerIpar + 'login', formData)
            .then((result) => {
                if (result.code === 200) {
                    this.getUserInfo(result.data.user_id, result.data);
                } else {
                    this.showLogin(false);
                    if (result.message === '用户不存在') {
                        DeviceEventEmitter.emit('toast', I18n.t('toast.loginUserNotExist'))
                    } else if (result.message === '密码错误') {
                        DeviceEventEmitter.emit('toast', I18n.t('toast.passwordNo'))
                    }
                }

            })
            .catch((error) => {
                this.showLogin(false);
                console.log('loginPage erroe--' + error);
                DeviceEventEmitter.emit('toast', I18n.t('toast.loginFail'))
            })
    }


    /**
     *  获取用户详细信息
     *  @param user_id
     *  @param defaultUserInfo 如果这个接口找不到用户信息的话我们使用defaultUserInfo
     */
    getUserInfo(user_id, defaultUserInfo) {

        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'user_id=' + user_id)
            .then((result) => {
                let _resultData = defaultUserInfo;
                if (result.code === 200) {
                    _resultData = result.data
                }
                this.loginComplete(_resultData)
            })
            .catch((error) => {
                console.log('login page getUserInfo error--: ' + error);
                this.loginComplete(defaultUserInfo)
            })
    }

    /**
     * 全部任务完成
     * @param userInfo
     */
    loginComplete(userInfo) {
        this.showLogin(false);
        CommonUtils.saveUserInfo(userInfo);


        if (userInfo.lang) {
            I18n.locale = userInfo.lang.toLowerCase();
            AsyncStorage.setItem('lang', userInfo.lang.toLowerCase());
        }
        for (let i = 0, len = this.countryData.length; i < len; i++) {
            if (this.countryData[i].iso === userInfo.country) {
                new CommonUtils().saveCountryData(this.countryData[i]);
            }
        }

        NativeModules.UMPushModule.addAlias(userInfo.main_user_id, 'IPAR_SHOP_ID', (code) => {
            console.log('ssss--UMPushModule---' + code)
        });

        DeviceEventEmitter.emit('toast', I18n.t('default.success'));

        const {navigator} = this.props;
        navigator.resetTo({
            component: SlideMenu,
            name: 'SlideMenu',
            params: {
                ...this.props,
                // isFirst: true,
            }
        });
    }


    /**
     * 点击
     * @param type
     * @private
     */
    _onClick(type) {
        let _component = null;
        switch (type) {
            case clickTypes.register:
                _component = SelectRegisterPage;
                break;
            case clickTypes.login:

                if (this.countryData === null) {
                    this.onLoadCountryData(true);
                } else {
                    this.startLogin();
                }

                // this.props.navigator.push({
                // 	component: RegisterIBMOnePage,
                // 	name: 'RegisterIBMOnePage',
                // 	params: {
                // 		userId: '21cf5023-5e53-3285-85bf-1eb324e0d2e4',
                // 	}
                // });

                break;
            case clickTypes.forgotPass:
                _component = FindPasswordPage;

                break;
        }
        if (_component) {
            this.props.navigator.push({
                component: _component,
                params: {
                    countryData: this.countryData
                }
            });
        }
    }

    /**
     * init
     * */
    render() {
        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    titleImage={require('../../res/images/ic_ipar_logo.png')}
                    barTextStyle={StatusBarTextStyle.black}
                    onClickLeftBtn={() => {
                        this.props.navigator.pop();
                    }}
                />

                <KeyboardAwareScrollView>
                    <Animated.View
                        style={[StyleUtils.center, styles.boxStyle, {opacity: this.state.fadeAnim,}]}>

                        {/*title*/}
                        {ViewUtils.getTitleView(I18n.t('default.login'),
                            I18n.t('default.donHaveAn'),
                            () => this._onClick(clickTypes.register))}


                        {/*input&btn*/}

                        {/*userName*/}
                        <IparInput
                            onChangeText={(text) => this.userName = text}
                            placeholder={I18n.t('default.iparIdUserName')}/>

                        {/*userPass*/}
                        <IparInput
                            isPassword={true}
                            onChangeText={(text) => this.userPass = text}
                            placeholder={I18n.t('default.enterPass')}/>


                        {ViewUtils.getButton(I18n.t('default.signIn'), () => this._onClick(clickTypes.login), StyleUtils.marginTop)}

                        <TouchableOpacity
                            onPress={() => this._onClick(clickTypes.forgotPass)}>
                            <Text
                                style={[StyleUtils.text, StyleUtils.smallFont, StyleUtils.marginTop]}>{I18n.t('default.forgotPass')}</Text>
                        </TouchableOpacity>
                    </Animated.View>

                </KeyboardAwareScrollView>


            </View>
        );
    }
}
const styles = StyleSheet.create({
    boxStyle: {
        padding: 16,
    },
});
